import { useEffect, useRef } from 'react'
// import { Canvas, Textbox } from 'fabric'
import { getIntervalAndframe, formatTimeLabel } from './utils/tools'
import { drawLine, canvasBasicType } from './utils/canvas'

type Timeline2Props = {
    duration: number // 总时长（秒）
    scale: number // 缩放级别（1到8）
    callBack: (width: number, cell: number) => void
}

const Timeline2 = ({ duration, scale, callBack = () => {} }: Timeline2Props) => {
    // const timeLineWidth = useRef<number>(0)
    const timeLineCanvasWidth = useRef<number>(0)
    const timeLine = useRef<HTMLCanvasElement>(null)
    const containerRef = useRef<HTMLDivElement>(null) // 父级容器的引用
    const canvasBasic: canvasBasicType = {
        canvasHeight: 50, // 画布高度
        lineCapWidth: 50, // 时间单元宽度
        canvasPadding: 20  // 俩端padding 不然会截断文字
    }
    const textConfig = {
        fontSize: 10,
        fontFamily: 'serif',
        originX: 'center',
        originY: 'center',
        fill: '#fff', // Text color
        selectable: false,
        evented: false,   // 禁止事件（如双击）
        hasControls: false, // 禁止拉伸控制
        hasBorders: false,  // 隐藏边框
    }
    const fps = 30

    // 初始化Canvas绘制
    const initCanvas = (timeLabels: string[]) => {
        const timeLineRef = timeLine.current;
        if (timeLineRef) {
            const { canvasHeight } = canvasBasic;
            const dpr = window.devicePixelRatio || 1; // 获取设备像素比
            console.log(dpr)
    
            // 设置 canvas 的实际宽高
            timeLineRef.width = timeLineCanvasWidth.current * dpr;
            timeLineRef.height = canvasHeight * dpr;
    
            // 设置 canvas 的样式宽高
            timeLineRef.style.width = `${timeLineCanvasWidth.current}px`;
            timeLineRef.style.height = `${canvasHeight}px`;
    
            const ctx = timeLineRef.getContext('2d')!;
            ctx.scale(dpr, dpr); // 处理设备像素比
    
            ctx.clearRect(0, 0, timeLineCanvasWidth.current, canvasHeight);
            drawLine(ctx, timeLabels, { ...canvasBasic, canvasWidth: timeLineCanvasWidth.current });
        }
    }
    // const  createPoint = (left: number) => {
    //     const { canvasHeight } = canvasBasic
    //     return new Textbox('·', {
    //         left, // Horizontal position
    //         top: canvasHeight / 2, // Vertical position, adjusted for each text
    //         fontSize: 10,
    //         fontFamily: 'serif',
    //         originX: 'center',
    //         originY: 'center',
    //         fill: '#fff', // Text color
    //         selectable: false,
    //         evented: false,   // 禁止事件（如双击）
    //         hasControls: false, // 禁止拉伸控制
    //         hasBorders: false,  // 隐藏边框
    //       })
    // }
    // const initCanvas2 = (timeLabels: string[]) => {
    //     const canvas = new Canvas(timeLine.current as HTMLCanvasElement)
    //     canvas.clear()
    //     canvas.setDimensions({
    //         width: timeLineCanvasWidth.current,
    //         height: canvasBasic.canvasHeight
    //     })
    //     const { canvasPadding, lineCapWidth, canvasHeight } = canvasBasic
    //     const halfLineCapWidth = lineCapWidth / 2
    //     const centerY = canvasHeight / 2
    //     const lastIndex = timeLabels.length - 1
    //     let index = 0 // 初始化索引
    //     const batchSize = 50 // 每批渲染的数量
    //     const renderBatch = () => {
    //         for (let i = 0; i < batchSize && index < timeLabels.length; i++, index++) {
    //             const left = canvasPadding + index * lineCapWidth
    //             const textObject = new Textbox(timeLabels[index], {
    //                 left,
    //                 top: centerY,
    //                 fontSize: 10,
    //                 fontFamily: 'serif',
    //                 originX: 'center',
    //                 originY: 'center',
    //                 fill: '#fff', // Text color
    //                 selectable: false,
    //                 evented: false,   // 禁止事件（如双击）
    //                 hasControls: false, // 禁止拉伸控制
    //                 hasBorders: false,  // 隐藏边框
    //             });
    //             canvas.add(textObject)
    //             if (index !== lastIndex) {
    //                 canvas.add(createPoint(left + halfLineCapWidth))
    //             } else { // 判断最后一个点是否显示
    //                 const lastDistance = timeLineCanvasWidth.current - left - canvasPadding;
    //                 if (lastDistance >= halfLineCapWidth) {
    //                     canvas.add(createPoint(left + halfLineCapWidth))
    //                 }
    //             }
    //         }
    //         if (index < timeLabels.length) {
    //             requestAnimationFrame(renderBatch); // 如果还有剩余，继续渲染下一批
    //         }
    //     }
    //     renderBatch()
    // }
    
    /**
 * 初始化时间线数据
 * @returns {string[]} 时间线标签数组
 */
    const initTimelineData = (): string[] => {
        let timeLineWidth = 0
        // 获取不同缩放等级的间隔和帧数间隔
        const { interval, frameInterval } = getIntervalAndframe(scale)
        // 计算时间间隔的数量
        const intervalCount = Math.floor(duration / interval)
        // 初始化时间线标签数组
        const timeLabels: string[] = []
        // 循环生成时间线标签
        for (let i = 0; i <= intervalCount; i++) {
            // 添加时间标签
            timeLabels.push(formatTimeLabel(i * interval))
            
            // 如果有帧数间隔，则添加帧标签
            if (frameInterval) {
                for (let f = frameInterval; f < fps; f += frameInterval) {
                timeLabels.push(`${f}f`)
                }
            }
        }
        const { lineCapWidth, canvasPadding } = canvasBasic
        // 计算时间线的总宽度
        timeLineWidth = (timeLabels.length - 1) * lineCapWidth
        // 计算每个单元格的宽度
        const cellWidth = frameInterval
        ? (fps / frameInterval) * lineCapWidth
        : lineCapWidth / interval
    
        // 计算剩余时间
        const intervalCountOver = duration % interval
        
        // 如果有剩余时间，则添加剩余时间的标签
        if (intervalCountOver) {
            if (frameInterval) {
                // 时间对应的总帧数
                const f = intervalCountOver * fps
                // 计算剩余时间的帧数
                const fOver = f % frameInterval
                // 循环添加剩余时间的帧标签
                for (let f = frameInterval; f < f; f += frameInterval) {
                    timeLabels.push(`${f}f`)
                    timeLineWidth += lineCapWidth
                }
                // 如果有剩余帧，则添加剩余帧的宽度
                if (fOver) {
                    timeLineWidth += (lineCapWidth / frameInterval) * fOver
                }
            } else {
                // 如果没有帧数，则添加剩余时间的宽度
                timeLineWidth += (lineCapWidth / interval) * intervalCountOver
            }
        }
        
        // 回调函数，传递时间线的总宽度和每个单元格的宽度
        callBack(timeLineWidth, cellWidth)
        
        // 计算时间线画布的总宽度
        timeLineCanvasWidth.current = timeLineWidth + canvasPadding * 2
        
        // 返回时间线标签数组
        return timeLabels
    }

    // 当Canvas大小、总时长或缩放级别变化时，重新绘制Canvas
    useEffect(() => {
        const timeLabels = initTimelineData()
        requestAnimationFrame(() => initCanvas(timeLabels))
        // initCanvas(timeLabels)
    }, [duration, scale])

    return (
        <div ref={containerRef} style={{ marginLeft: '-20px' }}>
            <canvas ref={timeLine}></canvas>
        </div>
    )
}

export default Timeline2
